﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Axe.Data.Mapping.Exceptions;
using System.Collections.ObjectModel;

namespace Axe.Data.Mapping.Attributes
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple=true, Inherited=true)]
    public class ForeignKeyAttribute : Attribute
    {
        public string PropertyName { get; protected set; }
        public Type EntityType {get; protected set;}

        public ForeignKeyAttribute(Type entity, string property)
        {
            MappingDescription targetDescr = MappingDescriptionBuilder.GetDescription(entity);

            if (targetDescr == null)
                throw new MappingException(entity,"Cannot reflect mapping for type {0}", entity.Name);

            if(!targetDescr.MappedFields.ContainsProperty(property))
                throw new MappingException(entity, "Entity {0} doesn't contains property {1}", entity.Name, property);

            EntityType = entity;
            PropertyName = property;
        }

        /// <summary>
        /// Initializes new instance of ForeignKeyAttribute with entity type, and
        /// property named to primary key of requested entity
        /// </summary>
        /// <param name="entity"></param>
        public ForeignKeyAttribute(Type entity)
        {
            EntityType = entity;

            MappingDescription targetDescr = MappingDescriptionBuilder.GetDescription(entity);
            if(!targetDescr.HasPrimaryKey)
                throw new MappingException(entity,"Cannot specify foreign key to entity {0}, because it doesn't have PK",entity.Name);

            PropertyName = targetDescr.PrimaryKey.Property.Name;
        }
    }

    public class ForeignKeyCollection : Collection<ForeignKeyAttribute>
    {
    }
}
